package com.cgs.query.handler.statement

import com.cgs.query.exception.QueryException

interface Dialect {

    companion object {
        fun getDialectByDbType(dbType: String): Dialect {
            return when (dbType) {
                "Mysql" -> {
                    MysqlDialect.INSTANCE
                }
                "Oracle" -> {
                    OracleDialect.INSTANCE
                }
                else -> {
                    throw QueryException("不支持的产品分页：$dbType")
                }
            }
        }
    }

    fun toPaginateSelect(sql: String): String

    fun toCountSelect(sql: String): String {
        return "Select count(*) from ( $sql ) s"
    }

    fun getStartAndEnd(pn: Int, ps: Int): Pair<Int, Int> {
        return Pair(pn, ps)
    }
}


/**
 * mysql
 */
enum class MysqlDialect : Dialect {

    INSTANCE;

    override fun toPaginateSelect(sql: String): String {
        return "select * from ( $sql ) s limit ?,?"
    }

    override fun getStartAndEnd(pn: Int, ps: Int): Pair<Int, Int> {
        return Pair((pn - 1) * ps, ps)
    }
}

/**
 * oracle
 */
enum class OracleDialect : Dialect {

    INSTANCE;

    override fun toPaginateSelect(sql: String): String {
        return "select * from ( select row_.*, rownum rownum_ from ( $sql ) row_ where rownum <= ? ) where rownum_ > ?"
    }

    override fun getStartAndEnd(pn: Int, ps: Int): Pair<Int, Int> {
        return Pair(pn * ps, (pn - 1) * ps)
    }
}